//
//  WJPermissionManager.swift
//  PDFSign
//
//  Created by 李永彬 on 2025/9/27.
//

import UIKit
import AVFoundation
import Photos

// MARK: - 权限类型枚举
enum WJPermissionType {
    case camera
    case photoLibrary
    case both
}

// MARK: - 权限状态枚举
enum WJPermissionStatus {
    case authorized
    case denied
    case restricted
    case notDetermined
    case limited // 仅相册有限访问权限
}

// MARK: - 权限管理类
class WJPermissionManager: NSObject {
    
    static let shared = WJPermissionManager()
    
    private override init() {
        super.init()
    }
}

// MARK: - 公共方法
extension WJPermissionManager {
    
    /// 检查权限状态
    func checkPermissionStatus(_ type: WJPermissionType) -> [WJPermissionType: WJPermissionStatus] {
        var results: [WJPermissionType: WJPermissionStatus] = [:]
        
        switch type {
        case .camera:
            results[.camera] = getCameraStatus()
        case .photoLibrary:
            results[.photoLibrary] = getPhotoLibraryStatus()
        case .both:
            results[.camera] = getCameraStatus()
            results[.photoLibrary] = getPhotoLibraryStatus()
        }
        
        return results
    }
    
    /// 请求权限
    func requestPermission(_ type: WJPermissionType, completion: @escaping ([WJPermissionType: WJPermissionStatus]) -> Void) {
        switch type {
        case .camera:
            requestCameraPermission { status in
                completion([.camera: status])
            }
        case .photoLibrary:
            requestPhotoLibraryPermission { status in
                completion([.photoLibrary: status])
            }
        case .both:
            let group = DispatchGroup()
            var results: [WJPermissionType: WJPermissionStatus] = [:]
            
            group.enter()
            requestCameraPermission { status in
                results[.camera] = status
                group.leave()
            }
            
            group.enter()
            requestPhotoLibraryPermission { status in
                results[.photoLibrary] = status
                group.leave()
            }
            
            group.notify(queue: .main) {
                completion(results)
            }
        }
    }
    
    /// 检查是否有权限（简化版）
    func hasPermission(_ type: WJPermissionType) -> Bool {
        let status = checkPermissionStatus(type)
        
        switch type {
        case .camera:
            return status[.camera] == .authorized
        case .photoLibrary:
            let photoStatus = status[.photoLibrary]
            return photoStatus == .authorized || photoStatus == .limited
        case .both:
            let cameraAuthorized = status[.camera] == .authorized
            let photoAuthorized = status[.photoLibrary] == .authorized || status[.photoLibrary] == .limited
            return cameraAuthorized && photoAuthorized
        }
    }
    
    /// 显示权限提示弹窗
    func showPermissionAlert(for type: WJPermissionType, in viewController: UIViewController, message: String? = nil) {
        let alertTitle: String
        let alertMessage: String
        
        switch type {
        case .camera:
            alertTitle = "Camera Access Denied"
            alertMessage = message ?? "Please allow camera access in Settings to take photos"
        case .photoLibrary:
            alertTitle = "Photo Library Access Denied"
            alertMessage = message ?? "Please allow photo library access in Settings to select photos"
        case .both:
            alertTitle = "Permission Denied"
            alertMessage = message ?? "Please allow camera and photo library access in Settings to use all features"
        }
        
        let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert)
        
        alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
        alert.addAction(UIAlertAction(title: "Go to Settings", style: .default) { _ in
            self.openAppSettings()
        })
        
        viewController.present(alert, animated: true)
    }
}

// MARK: - 私有方法
private extension WJPermissionManager {
    
    // MARK: 相机权限
    func getCameraStatus() -> WJPermissionStatus {
        let status = AVCaptureDevice.authorizationStatus(for: .video)
        
        switch status {
        case .authorized:
            return .authorized
        case .denied:
            return .denied
        case .restricted:
            return .restricted
        case .notDetermined:
            return .notDetermined
        @unknown default:
            return .denied
        }
    }
    
    func requestCameraPermission(completion: @escaping (WJPermissionStatus) -> Void) {
        let currentStatus = getCameraStatus()
        
        if currentStatus != .notDetermined {
            completion(currentStatus)
            return
        }
        
        AVCaptureDevice.requestAccess(for: .video) { granted in
            DispatchQueue.main.async {
                completion(granted ? .authorized : .denied)
            }
        }
    }
    
    // MARK: 相册权限
    func getPhotoLibraryStatus() -> WJPermissionStatus {
        let status = PHPhotoLibrary.authorizationStatus()
        
        switch status {
        case .authorized:
            return .authorized
        case .denied:
            return .denied
        case .restricted:
            return .restricted
        case .notDetermined:
            return .notDetermined
        case .limited:
            return .limited
        @unknown default:
            return .denied
        }
    }
    
    func requestPhotoLibraryPermission(completion: @escaping (WJPermissionStatus) -> Void) {
        let currentStatus = getPhotoLibraryStatus()
        
        if currentStatus != .notDetermined {
            completion(currentStatus)
            return
        }
        
        PHPhotoLibrary.requestAuthorization { status in
            DispatchQueue.main.async {
                let wjStatus: WJPermissionStatus
                switch status {
                case .authorized:
                    wjStatus = .authorized
                case .denied:
                    wjStatus = .denied
                case .restricted:
                    wjStatus = .restricted
                case .limited:
                    wjStatus = .limited
                case .notDetermined:
                    wjStatus = .notDetermined
                @unknown default:
                    wjStatus = .denied
                }
                completion(wjStatus)
            }
        }
    }
    
    /// 打开应用设置
    func openAppSettings() {
        guard let settingsUrl = URL(string: UIApplication.openSettingsURLString),
              UIApplication.shared.canOpenURL(settingsUrl) else {
            return
        }
        
        UIApplication.shared.open(settingsUrl)
    }
}

// MARK: - 便捷使用方法
extension WJPermissionManager {
    
    /// 便捷方法：检查并请求相机权限
    func checkAndRequestCameraPermission(completion: @escaping (Bool) -> Void) {
        let status = getCameraStatus()
        
        switch status {
        case .authorized:
            completion(true)
        case .denied, .restricted:
            completion(false)
        case .notDetermined:
            requestCameraPermission { newStatus in
                completion(newStatus == .authorized)
            }
        case .limited:
            completion(false) // 相机没有limited状态
        }
    }
    
    /// 便捷方法：检查并请求相册权限
    func checkAndRequestPhotoLibraryPermission(completion: @escaping (Bool) -> Void) {
        let status = getPhotoLibraryStatus()
        
        switch status {
        case .authorized, .limited:
            completion(true)
        case .denied, .restricted:
            completion(false)
        case .notDetermined:
            requestPhotoLibraryPermission { newStatus in
                completion(newStatus == .authorized || newStatus == .limited)
            }
        }
    }
    
    /// 便捷方法：准备使用相机（包含权限检查和提示）
    func prepareForCameraUsage(in viewController: UIViewController, completion: @escaping (Bool) -> Void) {
        checkAndRequestCameraPermission { granted in
            if granted {
                completion(true)
            } else {
                DispatchQueue.main.async {
                    self.showPermissionAlert(for: .camera, in: viewController)
                    completion(false)
                }
            }
        }
    }
    
    /// 便捷方法：准备使用相册（包含权限检查和提示）
    func prepareForPhotoLibraryUsage(in viewController: UIViewController, completion: @escaping (Bool) -> Void) {
        checkAndRequestPhotoLibraryPermission { granted in
            if granted {
                completion(true)
            } else {
                DispatchQueue.main.async {
                    self.showPermissionAlert(for: .photoLibrary, in: viewController)
                    completion(false)
                }
            }
        }
    }
    
    /// 便捷方法：准备使用相机和相册
    func prepareForCameraAndPhotoLibraryUsage(in viewController: UIViewController, completion: @escaping (Bool) -> Void) {
        requestPermission(.both) { results in
            let cameraGranted = results[.camera] == .authorized
            let photoGranted = results[.photoLibrary] == .authorized || results[.photoLibrary] == .limited
            
            if cameraGranted && photoGranted {
                completion(true)
            } else {
                DispatchQueue.main.async {
                    self.showPermissionAlert(for: .both, in: viewController)
                    completion(false)
                }
            }
        }
    }
}

// MARK: - 使用示例
/*
// 1. 检查权限状态
let status = WJPermissionManager.shared.checkPermissionStatus(.both)
print("Camera status: \(status[.camera]!)")
print("Photo library status: \(status[.photoLibrary]!)")

// 2. 请求相机权限
WJPermissionManager.shared.requestPermission(.camera) { results in
    if results[.camera] == .authorized {
        print("Camera permission granted")
    } else {
        print("Camera permission denied")
    }
}

// 3. 便捷使用 - 准备使用相机
WJPermissionManager.shared.prepareForCameraUsage(in: self) { granted in
    if granted {
        // 打开相机
        self.openCamera()
    }
}

// 4. 便捷使用 - 准备使用相册
WJPermissionManager.shared.prepareForPhotoLibraryUsage(in: self) { granted in
    if granted {
        // 打开相册
        self.openPhotoLibrary()
    }
}

// 5. 检查是否有权限
if WJPermissionManager.shared.hasPermission(.camera) {
    print("App has camera permission")
}
*/
